package com.bawan.location.Service;

import com.bawan.location.bo.ServerLocationBo;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;

/**
 * Desc:
 * User: ZhengCongChun
 * Date: 13-11-5
 * Time: 上午10:00
 *
 * @Version 1.0
 */
@Component
public class LocationServiceImpl implements ILocationService {
    @Override
    public ServerLocationBo getLocation(String ipAddress) {
        String dateFile = "location/GeoLiteCity.dat";

        return getLocation(ipAddress, dateFile);
    }

    private ServerLocationBo getLocation(String ipAddress, String locationDataFile) {
        ServerLocationBo serverLocation = null;
        URL url = getClass().getClassLoader().getResource(locationDataFile);

        if (url == null) {
            System.err.println("location database is not found - " + locationDataFile);

        } else {
            try {
                serverLocation = new ServerLocationBo();

                LookupService lookup = new LookupService(url.getPath(),
                        LookupService.GEOIP_MEMORY_CACHE);
                Location locationServices = lookup.getLocation(ipAddress);

                serverLocation.setCountryCode(locationServices.countryCode);
                serverLocation.setCountryName(locationServices.countryName);
                serverLocation.setRegion(locationServices.region);
                serverLocation.setRegionName(regionName.regionNameByCode(
                        locationServices.countryCode, locationServices.region));
                serverLocation.setCity(locationServices.city);
                serverLocation.setPostalCode(locationServices.postalCode);
                serverLocation.setLatitude(
                        String.valueOf(locationServices.latitude));
                serverLocation.setLongitude(
                        String.valueOf(locationServices.longitude));
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }

        return serverLocation;
    }
}
